<template>
  <div class="app-container">
    <div class="flex flex-items-center flex-justify-between pb-20px">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <div>
          <el-form-item prop="username">
            <el-input v-model="searchData.keyword" :placeholder="$t('adv.广告标题')+'...'" clearable/>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" round :icon="Search" @click="handleSearch">
              {{$t('common.搜索')}}
            </el-button>
          </el-form-item>
        </div>
      </el-form>
      <div>
        <el-button type="primary" round @click="createAdv">{{$t('adv.新增广告')}}</el-button>
        <el-button type="info" round class="info-self-btn color-#4E5969 mr-16px" @click="onBatchDelete">
          {{$t('adv.批量删除')}}
        </el-button>
        <el-select v-model="searchData.status" placeholder="全部" w100px popper-class="select-self-clas" >
          <el-option v-for="item in statusList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </div>
    </div>

    <div class="table-wrapper" v-loading="loading">
      <el-table
        :data="tableData"
        fixed="left"
        header-cell-class-name="cell-self-clas"
        cell-class-name="cell-class-name"
        :row-class-name="tableRowClassName"
         row-key="id"
        size="large"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection"  width="55" />
        <el-table-column :prop="CL('name')" :label="$t('adv.广告标题')" align="center" fixed min-width="160"> </el-table-column>
        <el-table-column prop="tfwz"  :label="$t('adv.投放位置')" align="center" min-width="102">
          <template #default="{ row }" >
            {{ row.tfwz == 0 ? $t('adv.商城') : $t('adv.店铺') }}
          </template>
        </el-table-column>
        <el-table-column prop="pic"  :label="$t('adv.广告图片')" align="center" min-width="132">
          <template #default="{ row }" >
            <el-image class="w-97px h-76px rounded-10px" :src="row[CL('pic')]" fit="fill"
            :preview-src-list="[row[CL('pic')]]" preview-teleported></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="sort" :label="$t('adv.排序') " align="center" min-width="73"> </el-table-column>
        <el-table-column prop="good"  :label="$t('adv.状态')" align="center" min-width="73">
          <template #default="{ row }" >
            <el-switch :active-value="1" :inactive-value="0" v-model="row.status" style="--el-switch-on-color: #13ce66; " :disabled="row.admin_status == 2 ? true : false" @change="onSwitchChangeStatus(row.status,row.id)"/>
          </template>
        </el-table-column>
        <el-table-column prop="createtime" :label="$t('adv.添加时间') " align="center" min-width="120"> </el-table-column>
        <el-table-column prop="pro" :label="$t('adv.商品链接') " align="center" min-width="185">
          <template #default="{ row }" >
            {{ locale=='zh' ?  row.pro?.name : row.pro?.name_ru }}
          </template>
        </el-table-column>
        <el-table-column prop="good"  :label="$t('adv.发布状态')" align="center" min-width="100">
          <template #default="{ row }">
            {{ [$t('adv.等待审核'),$t('adv.审核通过'),$t('adv.强制下架') ][row.admin_status] }}
          </template>
        </el-table-column>

        <el-table-column fixed="right" :label="$t('common.操作')" width="222" align="center">
          <template #default="{row}">
            <el-button type="primary"  round @click="handleEdit(row)">
               {{$t('shop.编辑')}}
            </el-button>
            <el-button type="info" round class="info-self-btn"  @click="handleDelete(row)">
               {{$t('shop.删除')}}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pager-wrapper mt-10px">
      <el-pagination :layout="paginationData.layout" :page-sizes="paginationData.pageSizes"
        :total="paginationData.total" :page-size="paginationData.pageSize" :current-page="paginationData.currentPage"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>


  </div>
</template>


<script lang="ts" setup>
import type { advData } from "@@/apis/adv/type"
import type { FormInstance  } from "element-plus"
const router = useRouter()
const route = useRoute()

import {  getbusinessAdvDataApi,adSetst,apiBusinessadvDel } from "@@/apis/adv"
import { usePagination } from "@@/composables/usePagination"
import {  Search } from "@element-plus/icons-vue"

import { useI18n } from 'vue-i18n';
const { locale, t } = useI18n();//登录国籍
import { inject } from 'vue'
const CL: any = inject("$CL");

const loading = ref<boolean>(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()

// region 查
const tableData = ref<advData[]>([])
const searchFormRef = ref<FormInstance | null>(null)
const statusList = ref([{
  label: t('common.全部'),
  value: -1,
}, {
  label: t('adv.已停用'),
  value: 0,
}, {
  label: t('adv.强制下架'),
  value: 2,
}])
const searchData = reactive({
  status: -1,
  keyword: '',
})


let state = route.query.state
if(state){
  searchData.status=Number(state)
}
watch(()=>searchData.status,(val)=> {
  getTableData();
})


function getTableData() {
  loading.value = true
  let obj={
    page: paginationData.currentPage,
    limit: paginationData.pageSize,
    status: searchData.status,
    keyword: searchData.keyword,
    is_cg: 0,
  }
  let list=['keyword']
    if(locale.value=='ru'){
            for (let key in obj) {
              list.forEach((item=>{
                if (key === item) {
                  obj[key + '_ru'] = obj[key]; // 将值赋给新 key
                  delete obj[key];     // 删除旧的 key
                }
              }))
            }
    }
  getbusinessAdvDataApi(obj).then(({ data }) => {
    paginationData.total = data.count
    tableData.value = data.list;
  }).catch(() => {
    tableData.value = []
  }).finally(() => {
    loading.value = false
  })
}
function handleSearch() {
  paginationData.currentPage === 1 ? getTableData() : (paginationData.currentPage = 1)
}


// 创建广告
const createAdv = ()=> {
  router.push('/adv/ShopCreateAdv/' + 0 + '?is_cg=' + 1)
}

// 切换状态
const onSwitchChangeStatus = async (status:number,id: string)=> {
  try {
    loading.value = true;
    await adSetst({
      ids: id,
      st: status,
      reason: '',
    })
    getTableData()
    loading.value = false;
  } catch (error) {
    loading.value = false;
  }

}

// endregion

// region 编辑

const selectionList = ref<{id: number}[]>([])

const handleEdit = (row:advData)=> {
  router.push('/adv/ShopCreateAdv/' + row.id + "?admin_status=" + row.admin_status)
}
// endregion
// region 删
function handleDelete(row: advData) {
  ElMessageBox.confirm(t('common.确认删除？'),  t('common.提示'), {
    confirmButtonText: t('common.确认'),
    cancelButtonText: t('common.取消'),
    type: "warning"
  }).then(() => {
    apiBusinessadvDel({
      ids: row.id,
    }).then(() => {
      ElMessage.success(t('common.删除成功'))
      getTableData()
    })
  })
}

// 批量删除
const onBatchDelete = ()=> {
  if ( selectionList.value.length === 0) {
    ElMessage.warning(t('common.请选择要删除的广告'))
    return;
  }
  let ids:number[] = [];
  toRaw(selectionList.value).forEach((ele)=> {
    ids.push(ele.id);
  })


  ElMessageBox.confirm(t('common.确认删除？'),  t('common.提示'), {
    confirmButtonText: t('common.确定'),
    cancelButtonText: t('common.取消'),
    type: "warning"
  }).then(() => {
    apiBusinessadvDel({
      ids: ids.join(','),
    }).then(() => {
      ElMessage.success(t('common.删除成功'))
      getTableData()
    })
  })
}


const handleSelectionChange = (e:{id: number}[])=> {
  selectionList.value = e;
}
// endregion





// 表格隔行变色
interface User {
  date: string
  name: string
  address: string
}
const tableRowClassName = ({
  row,
  rowIndex,
}: {
  row: User
  rowIndex: number
}) => {
  if (rowIndex % 2 == 0) {
    return 'primary-row-color'
  } else {
    return 'info-row-color'
  }
}




// 监听分页参数的变化
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })
</script>


<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}




.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}


.app-container {
  display: flex;
  flex-direction: column;
  overflow: hidden;
  // 筛选项重置
  .el-form {
    .el-form-item {
      margin-bottom: 0;

      :deep(.el-form-item__content) {
        .el-date-editor {
          border-radius: 16px;
          background: #F2F3F5;
          box-shadow: 0px 2px 2px 0px rgba(45, 45, 45, 0.10);
        }
      }

      .el-input {
        :deep(.el-input__wrapper) {
          border-radius: 16px;
          box-shadow: 0px 2px 2px 0px rgba(45, 45, 45, 0.10);
          background: #F2F3F5;
        }

      }
    }

  }

  .el-select {
    :deep(.el-select__wrapper) {
      border-radius: 16px;
      background: #007AFF;

      .el-select__placeholder {
        color: #fff;
      }

      .el-select__suffix {
        .el-icon {
          color: #fff;
        }
      }
    }
  }



  .table-wrapper {
    flex: 1;
    overflow: hidden;
    .el-table {
      height: 100%;
      border-top-left-radius: 30px;
      border-top-right-radius: 30px;

      :deep(.cell-self-clas) {
        color: #1D2129 !important;
        font-size: 14px;
        font-weight: 400;
        background: #F2F3F5;
        // box-shadow: 0px 2px 2px 0px rgba(45, 45, 45, 0.10);
        border-right: none;
      }

      :deep(.cell-class-name) {
        color: #1D2129 !important;
        font-size: 14px;
        font-weight: 400;
      }
    }

  }

  .order-wrapper {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 50px;
    .left-text {
      color: #1D2129;
      font-size: 14px;
      font-weight: 400;
    }
  }
}

:deep(.dialog-wrapppx) {
  background: linear-gradient(to right,#FBFCFD,#F5F9FD,#ECF6FD);
}

.info-self-btn {
  background: #F2F3F5;
  box-shadow: 0px 2px 2px 0px rgba(45, 45, 45, 0.10);
  color: #1D2129;
  border-color: transparent;
}


</style>

